namespace SimpleWebServices.Web.Mvc
{
    using System;
    using System.Collections.Generic;
    using System.Net.Mime;

    [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
    public sealed class ContentNegotiationAttribute : Attribute
    {
        private string _extension;
        private string _mediaTypes;

        public ContentNegotiationAttribute()
            : this(".html", "*/*")
        {
        }

        public ContentNegotiationAttribute(string extension, string mediaTypes)
        {
            this.Extension = extension;
            this.MediaTypes = mediaTypes;
        }

        public string Extension
        {
            get
            {
                return this._extension;
            }

            private set
            {
                if (null == value)
                {
                    throw new ArgumentNullException("value");
                }
                else if (0 == value.Length)
                {
                    throw new ArgumentOutOfRangeException("value");
                }
                else if (value.StartsWith(".", StringComparison.OrdinalIgnoreCase))
                {
                    this._extension = value.Substring(1);
                }
                else
                {
                    this._extension = value;
                }
            }
        }

        public string MediaTypes
        {
            get
            {
                return this._mediaTypes;
            }

            private set
            {
                if (null == value)
                {
                    throw new ArgumentNullException("value");
                }
                else if (0 == value.Length)
                {
                    throw new ArgumentOutOfRangeException("value");
                }

                this._mediaTypes = value;
            }
        }

        public IEnumerable<ContentType> ToContentTypes()
        {
            List<ContentType> result = new List<ContentType>();

            string[] parts = this.MediaTypes.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string part in parts)
            {
                result.Add(new ContentType(part.Trim()));
            }

            return result;
        }
    }
}